from django import http
from django.shortcuts import redirect
from django.views import View
import json

class JSON_dataView(View):
    def get(self,request):
        json_d ={
            "dw":"Dwa",
            "dwa":"QWd",
        }
        return http.JsonResponse(json_d)

class RedirectView(View):
    """
    重定向首页
    """
    def get(self,request):
        return redirect('/users/register/')

class RegisterView(View):
    """用户注册类视图
    http://127.0.0.1:8000/users/register/
    """

    def get(self, request):
        """
        处理GET请求，返回注册页面
        :param request: 请求对象，包含了请求报文信息
        :return: 响应对象，用于构造响应报文，并响应给用户
        """
        return http.HttpResponse('这里假装返回注册页面')

    def post(self, request):
        """
        处理POST请求，实现注册逻辑
        :param request: 请求对象，包含了请求报文信息
        :return: 响应对象，用于构造响应报文，并响应给用户
        """
        return http.HttpResponse('这里假装实现注册逻辑')

class QSParamView(View):
    """测试提取查询字符串参数
    http://127.0.0.1:8000/querystring/?name=zxc&age=18
    """

    def get(self, request):
        # 获取查询字符串参数name、age
        name = request.GET.get('name', '小明')
        age = request.GET.get('age', '0')
        print(name,age)
        return http.HttpResponse('查询字符串参数：')

class FormDataParamView(View):
    """测试提取表单类型请求体参数
    http://127.0.0.1:8000/formdata/
    """

    def post(self, request):
        # 获取表单类型请求体参数中的username、password
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(username,password)
        return http.HttpResponse('表单类型请求体参数：')

class JSONParamView(View):
    """测试提取非表单类型请求体参数
    http://127.0.0.1:8000/json/
    """

    def post(self, request):
        # 获取请求体中原始的JSON数据
        json_str = request.body
        # 使用json模块将原始的JSON数据转字典
        json_dict = json.loads(json_str)
        # 提取JSON数据中的参数
        username = json_dict.get('username')
        password = json_dict.get('password')
        print(username,password)
        return http.HttpResponse('非表单类型请求体参数：')

class URLParam1View(View):
    """测试path()提取普通路径参数
    http://127.0.0.1:8000/url_param1/18/
    """

    def get(self, request, age):
        """
        :param age: 路由提取的关键字参数
        """
        print(age)
        return http.HttpResponse('测试path()提取普通路径参数：%s' % age)

class URLParam2View(View):
  """测试path()中自定义路由转换器提取路径参数：手机号
  http://127.0.0.1:8000/url_param2/18500001111/
  """

  def get(self, request, phone_num):
      """
      :param phone_num: 路由提取的关键字参数
      """
      print(phone_num)
      return http.HttpResponse('测试path()提取路径参数手机号：%s' % phone_num)

class URLParam3View(View):
    """测试re_path()提取路径参数
    http://127.0.0.1:8000/url_param3/18500001111/
    """

    def get(self, request, phone_num):
        """
        :param phone_num: 路由提取的关键字参数
        """
        print(phone_num)
        return http.HttpResponse('测试re_path()提取路径参数：%s' % phone_num)